package hut.ai.team.inf;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;

public class Button extends Actor implements IClickable {

	private OnClickListener listener;
	private TextureRegion region;
	private boolean isLed = false;

	public Button(TextureRegion region) {
		this.region = region;
		float width = region.getRegionWidth();
		if (width < 0) {
			width = -width;
		}
		float height = region.getRegionHeight();
		if (height < 0) {
			height = -height;
		}
		setSize(width, height);
		isLed = false;
	}

	private int count = 0;

	@Override
	public void act(float delta) {
		super.act(delta);
		if (isLed) {
			count++;
			if (count > 15 && count <= 30) {
				this.setVisible(false);
				if (count == 30) {
					count = 0;
				}
			} else {
				this.setVisible(true);

			}
		}
	}

	@Override
	public void onTouchDown() {
		Color c = getColor();
		c.r = 0.8f;
		c.g = 0.8f;
		c.b = 0.8f;
	}

	@Override
	public void onTouchUp() {
		Color c = getColor();
		c.r = 1f;
		c.g = 1f;
		c.b = 1f;
		if (listener != null) {
			listener.onClick(this);
		}
	}

	public void setOnClickListener(OnClickListener v) {
		this.listener = v;
	}

	public void setBackground(TextureRegion bg) {
		this.region = bg;
		float width = region.getRegionWidth();
		if (width < 0) {
			width = -width;
		}
		float height = region.getRegionHeight();
		if (height < 0) {
			height = -height;
		}
		setSize(width, height);
	}

	@Override
	public void draw(SpriteBatch batch, float parentAlpha) {
		Color color = getColor();
		Color old = batch.getColor();
		batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
		float x = getX();
		float y = getY();
		float scaleX = getScaleX();
		float scaleY = getScaleY();
		if (region != null) {
			float rotation = getRotation();
			if (scaleX == 1 && scaleY == 1 && rotation == 0) {
				batch.draw(region, x, y, getWidth(), getHeight());
			} else {
				batch.draw(region, x, y, getOriginX(), getOriginY(), getWidth(), getHeight(), scaleX, scaleY, rotation);
			}
		}
		batch.setColor(old);
		super.draw(batch, parentAlpha);
	}

	public boolean isLed() {
		return isLed;
	}

	public void setLed(boolean isLed) {
		this.isLed = isLed;
	}

}
